package cn.itsource.user.controller;

import cn.itsource.basic.utils.AjaxResult;
import cn.itsource.user.constant.WechatConstant;
import cn.itsource.user.domain.dto.LoginInfoDto;
import cn.itsource.user.service.IWechatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.Map;

@Controller
@RequestMapping("/wechat")
public class WechatController {

    @Autowired
    private IWechatService wechatService;


    /**
     * 拉起二维码
     * @return
     */
    @RequestMapping("/toLogin")
    public String toLogin(){
        String codeUrl = WechatConstant.CODE_URL.replace("APPID", WechatConstant.APPID)
                .replace("REDIRECT_URI", WechatConstant.REDIRECT_URI);
        //重定向到指定的 路径
        return "redirect:" + codeUrl;
    }


    /**
     * 二维码扫描成功后，跳转到回调接口，并且携带授权码
     * @param code
     * @return
     */
    @RequestMapping("/callback")
    public String callback(String code){
        return "redirect:http://localhost:8082/callback.html?code="+code;
    }


    /**
     * 处理回调接口
     * @return
     */
    @PostMapping("/handleCallback")
    @ResponseBody// 1.响应结果值必须是json格式   2.凡是异步请求，必须加此注解
    public AjaxResult handleCallback(@RequestBody Map<String,String> param){
        try {
            //处理回调接口
            Map<String, Object> resultMap = wechatService.handleCallback(param.get("code"));

            return AjaxResult.me().setResultObj(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }


    /**
     * 微信和手机用户进行绑定
     * @param loginInfoDto
     * @return
     */
    @PostMapping("/binder")
    @ResponseBody
    public AjaxResult binder(@RequestBody LoginInfoDto loginInfoDto){
        try {
            Map<String, Object> resultMap = wechatService.binder(loginInfoDto);
            return AjaxResult.me().setResultObj(resultMap);
        } catch (Exception e) {
            e.printStackTrace();
            return new AjaxResult(e.getMessage());
        }
    }

}
